<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
	<link href="/css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
	<link href="/css/font-awesome.css?v=4.4.0" rel="stylesheet">
	<link rel="stylesheet" href="/css/plugins/jQueryUI/jquery-ui.css"/>
	<style type="text/css">
		* {
			font-family: HP Simplified Light, "microsoft yahei";
			font-size: 14px;
		}
		::-moz-placeholder { color: #ccc; }
		::-webkit-input-placeholder { color:#ccc; }
		:-ms-input-placeholder { color:#ccc; }
		dl{
			margin-bottom: 0;
		}
		label{
			margin-bottom: 0;
		}
		ul li{
			list-style-type: square;
		}
		legend{
			padding: 5px 30px;
		}
		input:not([type=radio]) {
			border: 0px;
			height: 29px;
			float: left;
			outline: none;
			text-indent: 10px;
			background: #fff;
			border-radius: 2px;
			text-decoration: none;
			line-height: 29px;
			border: 1px solid #ccc;
		}

		button{
			float:right;
			font-size: 13px;
			height: 26px;
			width: 80px;
			border: 1px solid #a152a1cc;
			border-radius: 2px;
			cursor: pointer;
			margin-top: -30px;
			margin-right: 300px;
			background-color:#a152a1cc;
			color:#fff;
		}

		button#deletAgent{
			float: none;
			font-size: 13px;
			height: 26px;
			border: 1px solid #ccc;
			border-radius: 2px;
			cursor: pointer;
			margin-left: 15px;
			margin-top: 6px;
			background-color: white;
			color: #444;
		}

		button#deletAgent:hover{
			border-color: #444;
		}

		#cancelDelegateBtn{
			float:right;
			font-size: 13px;
			height: 26px;
			border: 1px solid #CCCCCC;
			border-radius: 2px;
			cursor: pointer;
			margin-top: -30px;
			margin-right: 395px;
			background-color:#fff;
			color:#666;
		}

		#cancelBtn{
			float:right;
			font-size: 13px;
			height: 26px;
			border: 1px solid #CCCCCC;
			border-radius: 2px;
			cursor: pointer;
			margin-top: -30px;
			margin-right: 395px;
			background-color:#fff;
			color:#666;
		}
		.popHeader{
			margin-bottom:5px;
			font-weight: 700;
			font-size:18px;
			color: #000;
			padding: 10px 20px;
    		background: #f6f6f6;
		}
		.signForm{
			padding:0px 30px;
		}
		.signForm input:not([type=radio]){
			width: calc(100% - 415px);
		}
		.pwd{
			margin-top: 5px;
			display:flex;
			flex-direction: row;
			/*justify-content: center;*/
			align-items: center;
		}
		.pwd > label:first-child{
			display:inline-block;
			width:112px;
			color: #737373;
			font-weight: 400;
			text-align: left;
			margin-right: 10px;
		}
		.error{
			color: red;
		}
		.ui-visual-focus {
			box-shadow: 0 0 0px 0px #a152a1cc;
		}
		.ui-state-active {
			border: 1px solid #a152a1cc;
			background: #a152a1cc;
			font-weight: normal;
			color: #ffffff;
		}
		#delegateInput + span{
			width: 18px;
			height: 18px;
			background: url(/img/search_icon.png) no-repeat center center;
			background-size: cover;
			position: absolute;
			right: 10px;
			top: 4px;
			display: block;
		}
		#delegateInputDiv{
			width: calc(100% - 415px);
			height: 29px;
			border: 1px solid #d7d7d7;
			float: left;
			position: relative;
		}
		#delegateInput {
			width: calc(100% - 30px);
			float: left;
			height: 100%;
			outline: none;
			font-size: 14px;
			text-indent: 1em;
			font-family: "HP Simplified Regular";
			border: 0;
			margin: 0;
			padding: 0;
			font-size: 1em;
			line-height: 1em;
			background-color: rgba(0, 0, 0, 0);
		}
		.searchedUerList {
			padding:5px !important;
			border:1px solid #f6f6f6;
		}

		.searchedUerList dt span{
			font-weight: normal;
			color:#444;
			font-size: 12px;
			padding:3px 0px 0px 50px;
		}

		.searchedUerList dd{
			font-size: 10px;
			color: #666;
			padding:0px 0px 0px 50px;
			font-weight:normal;
		}

		.searchedUerIcon{
			position: absolute;
			left: 12px;
			border-radius: 50%;
			margin-top: -19px;
			padding: 0;
			width: 32px;
		}
		.ui-button:active{
			border: 1px solid #c5c5c5;
			background: #f6f6f6;
			font-weight: normal;
			color: #454545;
		}
		.ui-button.ui-state-active:hover {
			border: 1px solid #a152a1cc;
			background: #a152a1cc;
			font-weight: normal;
			color: #ffffff;
		}

	</style>
</head>
<body>
	</div>
		<div class="popHeader">
			<span>Set delegate approver</span>
		</div>
		<legend>
			<span>Note</span>
				<ul>
					<li>
						An approver delegate can be specified, who will make decisions on behalf of the original approver during a specific period of time
					</li>
					<li>
						Appointment period is operated based on the Beijing/China(GMT+8) time zone.
					</li>
				</ul>
				<button type="button" id="modifyDelegateBtn">Modify</button>
				<button type="button" id="cancelDelegateBtn" hidden>Cancel</button>
				<button type="button" id="saveDelegateBtn" hidden>Save</button>
		</legend>
		<form id="delegateForm" class="signForm">
			<div class="pwd">
				<label>Delegate options:</label>
				<label id="selectOptionLabel" style="font-size: 13px">未设定</label>
				<div id="optionBtnGroup" hidden>
					<label for="radio-1" style="font-size: 13px">Specified</label>
					<input type="radio" name="radio-1" id="radio-1" value="1">
					<label for="radio-2" style="font-size: 13px">Not specified</label>
					<input type="radio" checked="checked" name="radio-1" id="radio-2" value="0">
				</div>
			</div>
			<div class="pwd">
				<label>Delegate period:</label>
				<label id="selectPeriodLabel" style="font-size: 13px">未设定</label>
				<input type="text" autocomplete="off" id="datepicker" name="datepicker" hidden readonly>
			</div>
			<div class="pwd">
				<label>Approver delegate:</label>
				<div id="selectAgentDiv">
					<label id="selectAgentLabel" style="font-size: 13px" data-agent="">未设定</label><button id="deletAgent" type="button" hidden onclick="deleteAgent()">Delete</button>
				</div>
				<div id="delegateInputDiv" hidden>
					<input type="text" id="delegateInput" name="delegateInput" value="" placeholder="Please enter approver by using the Instant Search or Add User icon." /><span></span>
				</div>
			</div>
		</form>
	<div>

	<div>
		<div class="popHeader" style="margin-top: 20px">
			<span>Change local password</span>
		</div>
		<legend>
			<span>Note</span>
			<ul>
				<li>Passwords should be 8 to 12 characters long, mixed with English letters, numbers, and special characters (!@#$%&*^).</li>
				<li>Cannot use your old password.</li>
				<li>Cannot use your ID as your password.</li>
			</ul>
			<button id="saveChangePwdBtn">Save</button>
		</legend>
		<form id="pwdForm" class="signForm">
				<div class="pwd">
					<label>Current password:</label>
					<input type="password" id="password0" name="password0" required="required">
				</div>
				<div class="pwd">
					<label>New password:</label>
					<input type="password" id="password1" name="password1" required="required">
				</div>
				<div class="pwd">
					<label>Confirm password:</label>
					<input type="password" id="password2" name="password2" required="required">
				</div>
		</form>
	</div>

	<div id="findPwd">
		<div class="popHeader" style="margin-top: 20px">
			<span>Manage find password</span>
		</div>
		<legend>
			<span>Note</span>
			<ul>
				<li>Its the place to enter the external mail information you can check when you forget your password.</li>
				<li>Please enter accurate information to easily retrieve your forgotten password.</li>
			</ul>
			<button id="modifyMailBtn" onclick="modifyMail()">Modify</button>
			<button id="cancelBtn" hidden onclick="cancelModify()">Cancel</button>
			<button id="registerMailBtn" hidden>Register</button>
		</legend>
		<div class="signForm">
			<form id="mailForm" class="pwd">
				<label>External mail:</label>
				<label id="externalMail"></label>
				<input type="text" id="mailInput" name="mailInput" required="required" hidden placeholder="Please enter mail.">
			</form>
		</div>
	</div>
	<p style="margin-bottom: 50px"></p>
	<!-- --------------------------------------------------------------->
	<script src="/js/jquery.min.js?v=2.1.4"></script>
	<script src="/js/jquery-ui.js?v=1.12.1"></script>
	<script src="/js/plugins/validate/jquery.validate.min.js"></script>
	<script src="/js/plugins/layer/layer.js"></script>
	<script src="/js/plugins/md5/jquery.md5.js"></script>
	<script src="/js/ajax-util.js"></script>

	<script type="text/javascript" language="html">
		$().ready(function() {
		    let index = layer.load(1, {
				shade: [0.5, '#0096D6'] //0.1透明度的白色背景
			});

		    $( "input[type=radio]" ).checkboxradio({
				 icon:false
			 });

		     $("#datepicker").datepicker({
				numberOfMonths: 2,
				dateFormat:'yy/mm/dd',
				onSelect: function( selectedDate ) {
					if(!$(this).data().datepicker.first){
						$(this).data().datepicker.inline = true
						$(this).data().datepicker.first = selectedDate;
					}else{
						if(selectedDate > $(this).data().datepicker.first){
							$(this).val($(this).data().datepicker.first+" - "+selectedDate);
						}else{
							$(this).val(selectedDate+" - "+$(this).data().datepicker.first);
						}
						$(this).data().datepicker.inline = false;
					}
				},
				onClose:function(){
					delete $(this).data().datepicker.first;
					$(this).data().datepicker.inline = false;
					if($(this).val().indexOf('-') == -1){
					    $(this).val('')
					}
				}
			});

			 $("#delegateInput").autocomplete({
				minLength: 2,
				source: function( request, response ) {
					$.ajax({
						method:'post',
						url: "/employee/empSearch/findByFullName",
						dataType: "json",
						data:{
							fullName: $("#delegateInput").val().trim().toLowerCase()
						},
						success: function(data) {
							response( $.map(data,function(item) {
								return {
									label: item.empNm+'  '+item.empJob,
									value: item.empMail,
									empId:item.empId,
									empNm:item.empNm,
									empDept:item.empDept,
									empJob:item.empJob,
									empManager:item.empManager,
									empMail:item.empMail
								}

							}));
						}
					});
				},

				create: function() {
					$(this).data('ui-autocomplete')._renderItem = function (ul,item){
						return $( "<li>" )
							.append( "<dl  class='searchedUerList'  >"+
								"<dt>"+
								"<span>"+item.label+"</span>"+
								"</dt>"+
								"<dd>"+
								"<img class='searchedUerIcon' src='/img/approval/user_icon.jpg' >"+
								"</dd>"+
								"<dd>"
								+item.empMail+
								"</dd>"+
								"</dl> ")
							.appendTo( ul );
					};
				},

				_renderMenu: function( ul, items ) {
					var that = this;
					$.each( items, function( index, item ) {
						that._renderItemData( ul, item );
					});
					$( ul ).find( "li:odd" ).addClass( "odd" );
				},

				_resizeMenu: function() {
					this.menu.element.outerWidth( 500 );
				},

				select: function ( event, ui ) {
					$("#selectAgentLabel").data('agent',ui.item.empId)
					$("#selectAgentLabel").text(ui.item.empNm + '/' + ui.item.empJob + '/' + ui.item.empMail);

					$("#delegateInputDiv").hide();
					$("#selectAgentDiv").show();
				},

				open: function() {
					$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
				},

				close: function() {
					$("#delegateInput").val('');
				},

				classes: {
					"ui-autocomplete": "highlight"
				},
				delay:800
			});

		     let animal = JSON.parse(sessionStorage.getItem("howAreYou"));
			 //$("#password0").focus();
			 $("#externalMail").text(animal.externalMail);
			 $("#mailInput").val(animal.externalMail);

			 $("#saveChangePwdBtn").on('click',function () {
				 $("#pwdForm").submit();
			 });
			 $("#registerMailBtn").on('click',function () {
				 $("#mailForm").submit();
			 });

			 $("#saveDelegateBtn").on('click',function () {
				 $("#delegateForm").submit();
			 });

			 validateRule();

			 $("#modifyDelegateBtn").on('click',function () {
				$("#modifyDelegateBtn").hide().siblings('button').show();
				$("#selectOptionLabel").hide();
				$("#selectPeriodLabel").hide();

				$("#optionBtnGroup").show();
				$("#datepicker").show();

				if($("#selectAgentLabel").data('agent') != ''){
				    $("#selectAgentDiv").show();
				    $("#deletAgent").css('display','inline-block');
				}else{
				    $("#selectAgentDiv").hide();
				    $("#delegateInputDiv").show();
				}

				$("#delegateForm").focus();
			 });

			 $("#cancelDelegateBtn").on('click',function () {
				$("#modifyDelegateBtn").show().siblings('button').hide();
				$("#optionBtnGroup").hide();
				$("#datepicker").hide();
				$("#delegateInputDiv").hide();
				$("#deletAgent").hide();
				$("#delegateForm label.error").remove();
				$("#delegateForm input").removeClass('error');

				$("#selectAgentDiv").show();
				$("#selectOptionLabel").show();
				$("#selectPeriodLabel").show();
			 });
			 loadDelegateMapping();
			 layer.close(index);
		});

		jQuery.validator.addMethod("notEqual", function(value, element, param) {
		 	return this.optional(element) || value != $(param).val();
		}, "Cannot use your old password.");

		jQuery.validator.addMethod("notEqualId", function(value, element, id) {
		 	return this.optional(element) || value != id;
		}, "Cannot use your ID.");

		$.validator.setDefaults({
			submitHandler : function(form) {
			    switch (form.id) {
					case 'pwdForm':
					    saveChangePwd();
					    break;
					case 'mailForm':
					    registerMail();
					    break;
					case 'delegateForm':
					    saveDelegate();
					    break;
				}
			}
		});

		function validateRule() {
			let icon = "<i class='fa fa-times-circle'></i> ";
			let animal = JSON.parse(sessionStorage.getItem("howAreYou"));
			$("#pwdForm").validate({
				rules: {
					password0: {
						required: true
					},
					password1: {
						required: true,
						notEqual: "#password0",
						notEqualId: animal.empId,
						minlength:8
					},
					password2: {
						equalTo: "#password1",
						minlength:8
					}
				},
				message:{

				},
				errorPlacement: function(error, element) {
					/*element.parent().after('<br/>').after(error);
					$(error).css( { marginLeft : "120px"} );*/
					//$(element).css( { marginRight : "10px"} );
					element.css( { marginRight : "10px"}).after(error);
				}
			});

			$("#mailForm").validate({
				rules: {
					mailInput: {
						required: true,
						email:true
					}
				},
				errorPlacement: function(error, element) {
					element.css( { marginRight : "10px"}).after(error);
				}
			})

			$("#delegateForm").validate({
				rules: {
					datepicker: {
						required: true
					},
					delegateInput: {
					    required: true
					}
				},
				errorPlacement: function(error, element) {
				    console.log(element)
					if(element[0].id == 'delegateInput'){
						element.parent().css( { marginRight : "10px"}).after(error);
					}
					else{
					    element.css( { marginRight : "10px"}).after(error);
					}
				}
			})
		}

		function modifyMail() {
			$("#modifyMailBtn").hide().siblings('button').show();
			$("#externalMail").hide();
			$("#mailInput").val($("#externalMail").text());
			$("#mailInput").show();
			$("#mailInput").focus();
		}

		function cancelModify() {
			$("#externalMail").show();
			$("#mailInput").hide();

			$("#modifyMailBtn").show();
			$('#cancelBtn').hide();
			$("#registerMailBtn").hide();
		}

		function saveChangePwd() {
		    let animal = JSON.parse(sessionStorage.getItem("howAreYou"));
		    let pwd0 = $('#password0').val().trim();
		    if(animal.password !== $.md5(animal.username+pwd0)){
		        $('#password0').focus();
		        layer.msg("原密码输入错误")
        		return false;
			}
		    let pwd1 = $('#password1').val().trim();
		    let pwd2 = $('#password2').val().trim();
		    if(pwd1 !== pwd2){
                    layer.msg("两次输入密码不一致")
                    return;
                }
			$.ajax({
                    url : "/approval/saveLocalPassword/"+pwd1,
                    type : "put",
                    success : function(r) {
                        if (r.code === 0) {
                            $("#pwdForm")[0].reset();
                            sessionStorage.setItem("howAreYou",JSON.stringify(r.hpUser));
                        } else {
                            alert(r.msg)
                        }
                    }
                });
		}

		function registerMail() {
		    if(!$('#mailForm').data('changed')){
		        cancelModify();
		        return;
			}

		    let newMail = $("#mailInput").val().trim();
			$.ajax({
				url : '/approval/saveExternalMail',
				data: {
				    externalMail: newMail
				},
				type : 'put',
				success : function(r) {
					if(r.code == 0){
					    sessionStorage.setItem("howAreYou",JSON.stringify(r.hpUser));
						$("#mailInput").hide();
						$('#cancelBtn').hide();
						$("#registerMailBtn").hide();
						$("#externalMail").text(newMail);
						$("#externalMail").show();
						$("#modifyMailBtn").show();
					}else{
						alert(r.msg);
					}
				}
			});
		}

		function deleteAgent() {
		    $("#selectAgentDiv").hide();
			$("#delegateInputDiv").show();
		}

		function loadDelegateMapping() {
			$.ajax({
				url : '/approval/query/listDelegateMapping',
				type : 'get',
				success : function(r) {
					if(r.code == 0){
					    if(r.result != null){
					        //赋值
							$("input[name='radio-1'][value='"+r.result.isEnabled+"']").attr('checked','true');
							$("#datepicker").val(r.result.startDate + ' - ' + r.result.endDate);
							$("#selectAgentLabel").data('agent',r.result.agentUserId)
							//设置显示文本
							$("#selectOptionLabel").text(r.result.isEnabled == '1'?'Specified':'Not specified');
							$("#selectPeriodLabel").text(r.result.startDate + ' - ' + r.result.endDate);
							$("#selectAgentLabel").text(r.result.agentInfo);
						}
					}else{
						layer.msg(r.msg);
					}
				}
			});
		}

		function saveDelegate() {
		    /*if(!$('#delegateForm').data('changed')){
		        cancelModify();
		        return;
			}*/

		    let period = $("#datepicker").val().trim().split('-'),
				agentUserId = $("#selectAgentLabel").data('agent'),
				option = $("input[name='radio-1']:checked").val();
			$.ajax({
				url : '/approval/saveDelegateMapping',
				data: {
				    option: option,
				    startDate: period[0].trim(),
				    endDate: period[1].trim(),
					agentUserId:agentUserId
				},
				type : 'post',
				success : function(r) {
					if(r.code == 0){
						$("#modifyDelegateBtn").show().siblings('button').hide();
						$("#optionBtnGroup").hide();
						$("#datepicker").hide();
						$("#delegateInputDiv").hide();
						$("#deletAgent").hide();
						$("#delegateForm label.error").remove();
						$("#delegateForm input").removeClass('error');

						$("#selectOptionLabel").text(option=='1'?'Specified':'Not specified');
						$("#selectPeriodLabel").text($("#datepicker").val().trim());

						$("#selectAgentDiv").show();
						$("#selectOptionLabel").show();
						$("#selectPeriodLabel").show();
					}else{
						layer.msg(r.msg);
					}
				}
			});
		}

	</script>
</body>
</html>